#include "lib_media_disk.h"
#include "lib_media_disk.private"

void disk_cb_read
(
    uint8_t buffer[],
    uint32_t iblock,
    uint32_t bytes
)
{
    disk_ans_t disk_ans;
    uint8_t    diskID;
    uint16_t   sector;
    uint8_t    count;
    uint32_t   i;

    if (False)
    {
    }
    else if ((uint32_t) iblock == (uint32_t) BLOCK_EOF)
    {
        printf("disk_cb_read sync");
    }
    else if (iblock >= DISK_BLOCK_N)
    {
        printf("DiskRead iblock=%ld,bytes=%ld\n", iblock, bytes);
        deadbeaf("disk_cb_read, not valid iblock");
    }
    else
    {
        diskID   = 0;
        sector   = iblock;
        count    = bytes;
        disk_ans = disk_read(diskID, buffer, sector, count);
    }
}

void disk_cb_write
(
    uint8_t buffer[],
    uint32_t iblock,
    uint32_t bytes
)
{
    disk_ans_t disk_ans;
    uint8_t    diskID;
    uint16_t   sector;
    uint8_t    count;
    uint32_t   i;

    if (False)
    {
		/*
		 * used in debug 
		 */
		 ;
    }
    else if ((uint32_t) iblock == (uint32_t) BLOCK_EOF)
    {
        printf("disk_cb_write sync");
    }
    else if (iblock >= DISK_BLOCK_N)
    {
        printf("DiskWrite iblock=%ld,bytes=%ld\n", iblock, bytes);
        deadbeaf("disk_cb_write, not valid iblock");
    }
    else
    {
        diskID   = 0;
        sector   = iblock;
        count    = bytes;
        disk_ans = disk_write(diskID, buffer, sector, count);
    }
}

void MediaBlockRead_disk
(
    OS_FILE_t *file,
    uint32_t iblock
)
{
    file->block = &file->blockLocal;
    disk_cb_read((p_uint8_t) file->block, iblock, DISK_BLOCK_SIZE);
}

void MediaBlockWrite_disk
(
    OS_FILE_t *file,
    uint32_t iblock
)
{
    disk_cb_write((p_uint8_t) file->block, iblock, DISK_BLOCK_SIZE);
}

uint32_t MediaBlockAlloc_disk(uint32_t size)
{
    uint32_t ans;

    ans = disk_bitmap_get_free_block();
    disk_bitmap_set_used_block(ans);

    return ans;
}

void MediaBlockUnAlloc_disk
(
    OS_FILE_t *file,
    uint32_t iblock
)
{
    uint8_t block[DISK_BLOCK_SIZE];

    my_memset(block, BLOCK_EMPTY, DISK_BLOCK_SIZE);
    disk_cb_write(block, iblock, DISK_BLOCK_SIZE);
    disk_bitmap_set_free_block(iblock);
    printf("MediaBlockUnAlloc_disk iblock=%lx\n", iblock);
}
